﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using VemTransporte.Models.Basica;
using VemTransporte.Models.Fachada;
using VemTransporte.Models.Factory;
using System.Globalization;

namespace VemTransporte.Views.UsuarioEmpresa
{
    public partial class CadastroParada : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Empresa empresaLogada = (Empresa)Session["EmpresaLogada"];

                if (empresaLogada != null)
                {
                    ImageEmpresaLogoTipo.ImageUrl = string.Format("/EmpresaLogos/{0}.jpg", empresaLogada.Id);
                    if (empresaLogada.TipoAcesso.Equals("ADMEMPRESA"))
                    {
                        liMenuEmpresaCadastro.Visible = true;
                        liMenuCadastroInicialEmpresa.Visible = false;
                        liMenuAlterarEndEmpresa.Visible = true;
                        liMenuCadastrarTelefones.Visible = true;
                        liMenuAlterarSenhaEmpresa.Visible = true;
                        liMenuAlterarLinhaEmpresa.Visible = false;
                        liMenuCadastroParadaEmpresa.Visible = false;
                        liMenuHoraLinhaEmpresa.Visible = false;
                        liMenuEmpresaVeiculo.Visible = true;
                    }
                    else if (empresaLogada.TipoAcesso.Equals("ADMTRANSPORTEPUBLICO"))
                    {
                        liMenuEmpresaCadastro.Visible = false;
                        liMenuCadastroInicialEmpresa.Visible = false;
                        liMenuAlterarEndEmpresa.Visible = false;
                        liMenuCadastrarTelefones.Visible = false;
                        liMenuAlterarSenhaEmpresa.Visible = false;
                        liMenuAlterarLinhaEmpresa.Visible = true;
                        liMenuCadastroParadaEmpresa.Visible = true;
                        liMenuHoraLinhaEmpresa.Visible = true;
                        liMenuEmpresaVeiculo.Visible = false;
                    }
                    else
                    {

                    }

                    if (empresaLogada.NomeFantasia.IndexOf(" ") > 0)
                    {
                        LabelNomeEmpresa.Text = empresaLogada.NomeFantasia.Substring(0, empresaLogada.NomeFantasia.IndexOf(" "));
                    }
                    else
                    {
                        LabelNomeEmpresa.Text = empresaLogada.NomeFantasia;
                    }

                        
                        GridViewParada.DataSource = Fachada.Instance.ProcurarParadaTodos();
                        GridViewParada.DataBind();
                }
                else
                {
                    Response.Redirect("LoginEmpresa.aspx", true);
                }
            }
        }

        protected void ButtonCadastrarParada_Click(object sender, EventArgs e)
        {
            try
            {
                ErrorMessage.Text = "";

                if (Fachada.Instance.ParadaAlterar != null)
                {
                    Fachada.Instance.ParadaAlterar.Numero = TextBoxNumero.Text;

                    string lati = TextBoxLatitude.Text.Substring(0, TextBoxLatitude.Text.IndexOf(".") + 7);
                    string log = TextBoxLongitude.Text.Substring(0, TextBoxLongitude.Text.IndexOf(".") + 7);
                    Fachada.Instance.ParadaAlterar.Latitude = double.Parse(lati.Replace(".", ","));
                    Fachada.Instance.ParadaAlterar.Longitude = double.Parse(log.Replace(".", ","));/**/

                    Fachada.Instance.Salvar(Fachada.Instance.ParadaAlterar);

                    Fachada.Instance.ParadaAlterar = null;

                    ButtonCadastrarParada.Text = "Cadastrar";

                    //ScriptManager.RegisterStartupScript(UpdatePanel1, typeof(Page), "MSG", "javascript:alert('Alterdo com sucesso!');", true);
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alterado", "alert('Alterado com sucesso!'); window.location='';", true);
                }
                else
                {
                    Parada par = ParadaFactory.Instance.CreateParada();

                    par.Numero = TextBoxNumero.Text;

                    string lati = TextBoxLatitude.Text.Substring(0, TextBoxLatitude.Text.IndexOf(".") + 7);
                    string log = TextBoxLongitude.Text.Substring(0, TextBoxLongitude.Text.IndexOf(".") + 7);
                    par.Latitude = double.Parse(lati.Replace(".", ","));
                    par.Longitude = double.Parse(log.Replace(".", ","));/**/

                    //par.Latitude = double.Parse(TextBoxLatitude.Text);
                    //par.Longitude = double.Parse(TextBoxLongitude.Text);/**/

                    Fachada.Instance.Salvar(par);

                    //ScriptManager.RegisterStartupScript(UpdatePanel1, typeof(Page), "MSG", "javascript:alert('Cadastro efetuado com sucesso!');", true);
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Cadastrar", "alert('Cadastrado com sucesso!'); window.location='';", true);

                    ErrorMessage.Text = "";

                }

                TextBoxNumero.Text = "";
                TextBoxLatitude.Text = "";
                TextBoxLongitude.Text = "";


            }
            catch (Exception ex)
            {
                ErrorMessage.Text = ex.Message;
            }
            finally
            {
                GridViewParada.DataSource = Fachada.Instance.ProcurarParadaTodos();
                GridViewParada.DataBind();
            }
        }

        protected void TextBoxNumeroLinha_TextChanged(object sender, EventArgs e)
        {

        }

        protected void GridViewParada_RowEditing(object sender, GridViewEditEventArgs e)
        {
            try
            {
                ErrorMessage.Text = "";

                Fachada.Instance.ParadaAlterar = Fachada.Instance.Paradas[e.NewEditIndex];

                TextBoxNumero.Text = Fachada.Instance.ParadaAlterar.Numero;
                TextBoxNumero.Focus();

                TextBoxLatitude.Text = Fachada.Instance.ParadaAlterar.Latitude.ToString().Replace(",", ".");
                TextBoxLongitude.Text = Fachada.Instance.ParadaAlterar.Longitude.ToString().Replace(",", ".");

                TextBoxNumero.Focus();

                ButtonCadastrarParada.Text = "Alterar";

                e.Cancel = true;
            }
            catch (Exception ex)
            {
                ErrorMessage.Text = ex.Message;
            }


        }

        protected void GridViewParada_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {

                string numero = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "numero"));

                ((ImageButton)e.Row.FindControl("ImageButtonExcluir")).CommandArgument = numero;

                ((ImageButton)e.Row.FindControl("ImageButtonExcluir")).Attributes.Add("onClick",
                       " return confirm('Confirma o cancelamento da parada nº " + numero + "?');");
            }

        }

        protected void GridViewParada_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "excluir")
            {
                try
                {
                    string numeroParada = e.CommandArgument.ToString();

                    foreach (Parada item in Fachada.Instance.Paradas.ToList())
                    {
                        if (item.Numero.Equals(numeroParada))
                        {
                            Fachada.Instance.Paradas.Remove(item);
                            //Fachada.Instance.Salvar(Fachada.Instance.LinhaAtual);
                            //ou
                            
                            Fachada.Instance.Remover(item);

                            break;
                        }
                    }

                    GridViewParada.DataSource = Fachada.Instance.Paradas;
                    GridViewParada.DataBind();

                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Excluir", "alert('Excluido com sucesso!'); window.location='MenuEmpresa';", true);

                }
                catch (Exception ex)
                {
                    ErrorMessage.Text = ex.Message;
                }
            }

        }

        protected void GridViewParada_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                this.GridViewParada.PageIndex = e.NewPageIndex;

                GridViewParada.DataSource = Fachada.Instance.Paradas;
                GridViewParada.DataBind();
            }
            catch (Exception ex)
            {
                ErrorMessage.Text = ex.Message;
            }
        }

        protected void GridViewParada_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            e.Cancel = true;
        }

        protected void GridViewParada_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
        }

        protected void GridViewParada_RowUpdated(object sender, GridViewUpdatedEventArgs e)
        {
        }


    }
}